import getopt
import sys
import httplib
import getpass
import base64
import urllib
import os.path
import datetime
from caldavclientlibrary.protocol.webdav.definitions import davxml
from caldavclientlibrary.protocol.url import URL
from caldavclientlibrary.protocol.webdav.propfind import PropFind
from caldavclientlibrary.protocol.webdav.propall import PropAll
from caldavclientlibrary.client.clientsession import CalDAVSession


#Utility fxn
def date_today():
	today = datetime.date.today()
	month = today.month
	if month < 10:
		month = "0" + str(month)
	day = today.day
	if day < 10:
		day = "0" + str(day)
	return str(today.year) + month + day

#Class to use a subset of open source caldav library
class CaldavConnection(CalDAVSession):

	def __init__(self, username, password, url, log):
		self.urlObj = URL(url)
		self.dateEventPairs = []
		#Setting the port parameter does not satisfy how later code looks for port info
		super(CaldavConnection, self).__init__(self.urlObj.server, root=self.urlObj.relativeURL(), ssl=True, user=username, pswd=password, logging=log)

	class Reservation:

		def __init__(self):
			self.name = ""
			self.project = ""
			self.host = []
			self.network = ""
			self.startTime = ""


	def get_events_today(self):
		results = self.getPropertiesOnHierarchy(self.urlObj, (davxml.resourcetype,))
		#results is a dict of href strings and PropFindResult objs
		eventIds = results.keys()
		#Find events for today
		for evId in eventIds:
			eData, etag = self.readData(URL(os.path.join(self.urlObj.absoluteURL(), evId)))
			self.dateEventPairs.extend( [(line, eData) for line in eData.splitlines() if line.startswith("DTSTART;TZID") or line.startswith("DTSTART;VALUE=") ] )

		#check what we have
		for (dt, ev) in self.dateEventPairs:
			print dt

		eventsToday = [ (dt,ev) for (dt, ev) in self.dateEventPairs if dt.rsplit(':',1)[1] == date_today() ]
		print "Today's Events:"
		print eventsToday

		reservations = []
		for (dt, ev) in eventsToday:
			res = Reservation()
			res.startTime = dt
			for line in ev.splitlines()
				if line.startswith("SUMMARY"):
					summary = line.rsplit(':',1)[1]
					#Fill in reservation

					break
			

def run(username, password, url, logging):
	#Create headers
	caldav = CaldavConnection(username, password, url, logging)
	caldav.get_events_today()


if __name__ == "__main__":
	options, args = getopt.getopt(sys.argv[1:], "l", ["user=","passwd=","url="])
	options = dict(options)
	if not "--url" in options:
		options["--url"] = raw_input("Enter url (include http:..) ")
	if not "--user" in options:
		options["--user"] = raw_input("Enter user name: ")
	if not "--passwd" in options:
		options["--passwd"] = getpass.getpass()
	logging = False
	if "-l" in options:
		logging = True
	#the url for events needs to end in '/'
	if not options["--url"].endswith("/"):
		options["--url"] += "/"
	run(options["--user"], options["--passwd"], options["--url"], logging)
